עקרונות שפות תכנות 2018 תרגול 8 Type Inference System
|
|
- Rolf Kennedy
- 5 years ago
- Views:
Transcription
1 עקרונות שפות תכנות 2018 תרגול 8 Type Inference System Type Inference System The Type Inference System is a TypeScript Implementation of the algorithm for Type Checking and Inference using Type Equations. System Architecture The system is built from the following modules: The layers of the system are: - Abstract Syntax for L5 Expressions and for Type Expressions - The key data types manipulated in the algorithm, Type Equations and Type Substitutions. - The logic of the algorithm is implemented in three functional packages: Exp-to-Pool, Exp-to-Equations and the top-level algorithm Solve. The key interfaces of each package are the following: 1
2 Layer 1: Languages Definitions The Type Inference algorithm maps expressions in one language (L5 expressions) into expressions in another language (Type Expressions). The lower level of the Type Inference system implements the Abstract Syntax interfaces for expressions in these two languages. L5-AST: Implements parser and abstract syntax for the following BNF concrete syntax: BNF // <program> ::= (L5 <exp>+) / Program(exps:List(exp)) // <exp> ::= <define> <cexp> / DefExp CExp // <define> ::= ( define <var-decl> <cexp> ) / DefExp(var:VarDecl, val:cexp) // <var> ::= <identifier> / VarRef(var:string) // <cexp> ::= <number> / NumExp(val:number) // <boolean> / BoolExp(val:boolean) // <string> / StrExp(val:string) // <prim-op> / PrimOp(op:string) // <var-ref> // ( lambda ( <var-decl>* ) (: <TExp>)? <cexp>+ ) / ProcExp(params:VarDecl[], body:cexp[], returnte: TExp)) // ( if <cexp> <cexp> <cexp> ) / IfExp(test: CExp, then: CExp, alt: CExp) // ( quote <sexp> ) / LitExp(val:SExp) // ( <cexp> <cexp>* ) / AppExp(operator:CExp, operands:cexp[])) // ( let ( <binding>* ) <cexp>+ ) / LetExp(bindings:Binding[], body:cexp[])) // ( letrec ( binding*) <cexp>+ ) / LetrecExp(bindings:Bindings[], body: CExp) // ( set! <var> <cexp>) / SetExp(var: varref, val: CExp) // <binding> ::= ( <var-decl> <cexp> ) / Binding(var:VarDecl, val:cexp) // <prim-op> ::= + - * / < > = not eq? string=? // cons car cdr list? number? // boolean? symbol? string? // display newline // <num-exp> ::= a number token // <bool-exp> ::= #t #f // <var-ref> ::= an identifier token / VarRef(var) // <var-decl> ::= an identifier token (var : TExp) / VarRef(var, TE: TExp) // <sexp> ::= symbol number bool string ( <sexp>* ) Note that we introduce optional type annotations in the L5 syntax in 2 places only: - As part of VarDecl in the form (var : type-expression) - As part of ProcExp in the return type of the procedure in the form: (lambda ((x : number) (y : number)) : number ) TExp-AST // Type language // <TExp> ::= <AtomicTExp> <CompoundTExp> <TVar> // <AtomicTExp> ::= <NumTExp> <BoolTExp> <StrTExp> <VoidTExp> // <NumTExp> ::= number // NumTExp() // <BoolTExp> ::= boolean // BoolTExp() // <StrTExp> ::= string // StrTExp() // <VoidTExp> ::= void // VoidTExp() // <CompoundTExp> ::= <ProcTExp> <TupleTExp> 2
3 // <NonTupleTExp> ::= <AtomicTExp> <ProcTExp> <TVar> // <ProcTExp> ::= [ <TupleTExp> -> <NonTupleTExp> ] // ProcTExp(param-tes: list(texp), returnte: TExp) // <TupleTExp> ::= <NonEmptyTupleTExp> <EmptyTExp> // <NonEmptyTupleTExp> ::= ( <NonTupleTExp> * )* <NonTupleTExp> // TupleTExp(tes: list(texp)) // <EmptyTExp> ::= empty // <TVar> ::= a symbol starting with T // TVar(id: Symbol, contents; Box(string undefined)) Examples of type expressions // number // boolean // void // (number -> boolean) // (number * number -> boolean) // (number -> (number -> boolean)) // (empty -> number) // (empty -> void) The definition of the TExp datatypes, the parser and the unparser of TExp is provided in file TExp.ts. Layer 2: Substitution and Equation ADTs The Type Inference algorithm is defined in terms of 2 basic formal tools: Type Substitutions are finite mappings of Type Variables to Type Expressions. Equations are pairs that state that a left Type Expression is to be held equivalent to a right Type Expression. Equations are the tool we use to represent a typing statement in the algorithm. Substitution ADT The interface of the Substitution ADT includes: makesub(variables, type-expressions) subget(sub, var): lookup a variable in a substitution extendsub(sub, var, te): create a new substitution by adding a single pair {var:te} to sub applysub(sub, te): replace type variables inside te according to sub combinesub(sub1, sub2): compute a new sub such that: applysub(sub, te) = applysub(sub2, applysub(sub1, te)) for all te. Equation ADT The interface includes: export interface Equation {left: T.TExp, right: T.TExp}; export const makeequation = (l: T.TExp, r: T.TExp): Equation => ({left: l, right: r}); 3
4 Layer 3: Exp-to-Pool, Exp-to-Equations, Solve exptopool(exp) traverses the AST of a Scheme Expression and maps each sub-expression in the AST to distinct Type Variables. pooltoequations(pool) applies type formulae to propagate constraints from the syntactic structure of the L5 Expression to constraints (equations) among the type variables of the pool. There are specific constraints derived for each type of syntactic construct according to the semantics of the L5 programming language. infer(l5expr) applies the whole logic of the type inference algorithm. The main steps of the algorithm are reflected in this top-level fragment: export const infertype = (exp: A.Exp): T.TExp => { const pool = exptopool(exp); const equations = pooltoequations(pool); const sub = solveequations(equations); const texp = inpool(pool, exp); if (T.isTVar(texp) &&! iserror(sub)) return S.subGet(sub, texp); else return texp; } The key logic of the algorithm lies in the solveequations algorithm which turns a list of Type Equations into a single coherent Type Substitution which satisfies all the constraints. solveequations() relies on the computation of unification between two type expressions as shown in the following fragment: // Purpose: Solve the type equations and return the resulting substitution // or error, if not solvable // Example: solveequations( // pooltoequations( // exptopool( // parse('((lambda (x) (x 11)) (lambda (y) y))')))) => sub export const solveequations = (equations: Equation[]): S.Sub Error => solve(equations, S.makeEmptySub()); // Purpose: Solve the equations, starting from a given substitution. // Returns the resulting substitution, or error, if not solvable const solve = (equations: Equation[], sub: S.Sub): S.Sub Error => { const solvevareq = (tvar: T.TVar, texp: T.TExp): S.Sub Error => { const sub2 = S.extendSub(sub, tvar, texp); return iserror(sub2)? sub2 : solve(rest(equations), sub2); }; const bothsidesatomic = (eq: Equation): boolean => T.isAtomicTExp(eq.left) && T.isAtomicTExp(eq.right); const handlebothsidesatomic = (eq: Equation): S.Sub Error => (T.isAtomicTExp(eq.left) && T.isAtomicTExp(eq.right) && T.eqAtomicTExp(eq.left, eq.right))? solve(rest(equations), sub) : Error(`Equation with non-equal atomic type ${eq}`); 4
5 } if (A.isEmpty(equations)) return sub; const eq = makeequation(s.applysub(sub, first(equations).left), S.applySub(sub, first(equations).right)); return T.isTVar(eq.left)? solvevareq(eq.left, eq.right) : T.isTVar(eq.right)? solvevareq(eq.right, eq.left) : bothsidesatomic(eq)? handlebothsidesatomic(eq) : (T.isCompoundTExp(eq.left) && T.isCompoundTExp(eq.right) && canunify(eq))? solve(r.concat(rest(equations), splitequation(eq)), sub) : Error(`Equation contains incompatible types ${eq}`); Compound type expressions are unified by unifying their components one by one. This is implemented by these 2 functions: // Signature: canunify(equation) // Purpose: Compare the structure of the type expressions of the equation const canunify = (eq: Equation): boolean => T.isProcTExp(eq.left) && T.isProcTExp(eq.right) && (eq.left.paramtes.length === eq.right.paramtes.length); // Signature: splitequation(equation) // Purpose: For an equation with unifyable type expressions, // create equations for corresponding components. // Type: [Equation -> List(Equation)] // Example: splitequation( // makeequation(parsetexp('(t1 -> T2)'), // parsetexp('(t3 -> (T4 -> T4))')) => // [ {left:t2, right: (T4 -> T4)}, // {left:t3, right: T1)} ] iscompoundexp(eq.left) && iscompoundexp(eq.right) && canunify(eq) const splitequation = (eq: Equation): Equation[] => (T.isProcTExp(eq.left) && T.isProcTExp(eq.right))? R.zipWith(makeEquation, R.prepend(eq.left.returnTE, eq.left.paramtes), R.prepend(eq.right.returnTE, eq.right.paramtes)) : []; 5
6 Exercise: Extend the Type Inference system to support "If" expressions The part of the Type Inference System which "knows" L5 Expressions is the function makeequationfromexp(exp, pool). The structure of this function is a case for each type of L5 expression. The code we provide supports: Procedure Application Number and Boolean Primitive Procedures Extend the code to support Scheme expressions of the type (if <test> <then> <alt>). Remember question 2 from last week's practical session. From Typing Rule for if-expressions the type equations derived from a composite if-expression: (if _p _c _a) we derive 3 equations: T c = T a T p = boolean T if = T c Accordingly, the code of the function makeequationfromexp is extended to process IfExp // Support if-expressions: // [if <test> <then> <else>) --> // {[T<test> = boolean], [T<then> = T<alt>], [T<then> = T<if>]} A.isIfExp(exp)? [makeequation(inpool(pool, exp.test), T.makeBoolTExp()), makeequation(inpool(pool, exp.then), inpool(pool, exp.alt)), makeequation(inpool(pool, exp), inpool(exp.alt))] : Review the code of the AppExp equation factory: // An application must respect the type of its operator // Type(Operator) = [T1 *.. * Tn -> Te] // Type(Application) = Te A.isAppExp(exp)? [makeequation(inpool(pool, exp.rator), T.makeProcTExp(R.map((e) => inpool(pool, e), exp.rands), inpool(pool, exp)))] : This should create one equation for each argument and one equation for the exp itself. Explain why it is not necessary to add an equation for the type of the exp itself. 6
7 // Implementation of the Substitution ADT // ======================================================== // A substitution is represented as a 2 element list of equal length // lists of variables and type expression. // The empty substitution is [[], []] export interface Sub {tag: "Sub"; vars: TVar[]; tes: TExp[]; }; export const issub = (x: any): x is Sub => x.tag === "Sub";.substitution עבור ADT נספח לעיון // Constructors: // Signature: makesub(vars, tes) // Purpose: Create a substitution in which the i-th element of 'variables' // is mapped to the i-th element of 'tes'. // Example: makesub( // map(parsete, ["x", "y", "z"]), // map(parsete, ["number", "boolean", "(number -> number)"]) // => {tag: "Sub", vars: [x y z], // tes: [numtexp, booltexp, ProcTexp([NumTexp, NumTexp])]} // makesub(map(parsete, ["x", "y", "z"]), // map(parsete, ["number", "boolean", "(z -> number)"])) // => error makesub: circular substitution // Pre-condition: (length variables) = (length tes) // the list variables has no repetitions (it is a set) export const makesub = (vars: TVar[], tes: TExp[]): Error Sub => { const nooccurrences = zipwith(checknooccurrence, vars, tes); if (hasnoerror(nooccurrences)) return {tag: "Sub", vars: vars, tes: tes}; else return Error(getErrorMessages(noOccurrences)); }; export const makeemptysub = (): Sub => ({tag: "Sub", vars: [], tes: []}); Whenever creating a substitution, we verify that the invariant holds that when a TVar is associated to a TExp, it does not occur inside the TExp. This is enforced by this function: // Purpose: when attempting to bind tvar to te in a sub - check whether tvar occurs in te. // Return error if a circular reference is found. export const checknooccurrence = (tvar: TVar, te: TExp): true Error => { const check = (e: TExp): true Error => istvar(e)? ((e.var === tvar.var)? Error(`Occur check error - circular sub ${tvar.var} in ${unparsetexp(te)}`) : true) : isatomictexp(e)? true : isproctexp(e)? (hasnoerror(map(check, e.paramtes))? check(e.returnte) : Error(getErrorMessages(map(check, e.paramtes)))) : Error(`Bad type expression ${e} in ${te}`); return check(te); }; 7
8 Note on how we compare two substitutions to perform tests In order to compare two substitutions, we normalize them by sorting their string representation and then compare the strings. This in effect achieves set equality: export const subtostr = (sub: S.Sub): string => `{${zipwith((v, t) => `${v.var}:${unparsetexp(t)}`, sub.vars, sub.tes). sort(). join(", ")}}`; // Compare 2 subs encoded as VarTe (set equality) export const eqsub = (sub1: S.Sub, sub2: S.Sub): boolean => deepequal(subtostr(sub1), subtostr(sub2)); Understand how to use applysub From L5-substitutions-ADT-tests.ts: // applysub { const sub1 = sub(["t1", "T2"], ["number", "boolean"]); const te1 = parsete("(t1 * T2 -> T1)"); if (! iserror(te1)) { const te2 = S.applySub(sub1, te1); assert(unparsetexp(te2) === "(number * boolean -> number)"); } } Understand how to use combinesub // {T1:(number -> S1), T2:(number -> S4)} o {T3:(number -> S2)} => // {T1:(number -> S1), T2:(number -> S4), T3:(number -> S2)} { const sub1 = sub(["t1", "T2"], ["(number -> S1)", "(number -> S4)"]); const sub2 = sub(["t3"], ["(number -> S2)"]); const expected = sub(["t1", "T2", "T3"], ["(number -> S1)", "(number -> S4)", "(number -> S2)"]); const res = S.combineSub(sub1, sub2); asserteqsub(res, expected); } 8
Principles of Programming Languages
Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Type Checking We return to the issue of type safety we discussed informally,
More information6.821 Programming Languages Handout Fall MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science
6.821 Programming Languages Handout Fall 2002 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science Problem Set 6 Problem 1: cellof Subtyping Do exercise 11.6
More informationPrinciples of Programming Languages
Principles of Programming Languages Slides by Dana Fisman based on book by Mira Balaban and lecuture notes by Michael Elhadad Lesson 15 Type Inference Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172
More informationScheme in Scheme: The Metacircular Evaluator Eval and Apply
Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,
More informationPrinciples of Programming Languages
Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished
More informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).
More informationLecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.
Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)
More information6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson
6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator
More information6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter
6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,
More informationעקרונות שפות תכנות, סמסטר ב' 2016 תרגול 7: הסקת טיפוסים סטטית. Axiomatic Type Inference
עקרונות שפות תכנות, סמסטר ב' 2016 תרגול 7: הסקת טיפוסים סטטית 1. Axiomatic type inference 2. Type inference using type constraints נושאי התרגול: Axiomatic Type Inference Definition (seen in class): A Type-substitution
More information;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for
Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy
More informationCSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018
CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018 Deliverables: Your code (submit to PLC server). A13 participation survey (on Moodle, by the day after the A13 due date). This is
More informationregsim.scm ~/umb/cs450/ch5.base/ 1 11/11/13
1 File: regsim.scm Register machine simulator from section 5.2 of STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS This file can be loaded into Scheme as a whole. Then you can define and simulate machines
More informationWhy do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.
.00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do
More informationIntroduction to Scheme
How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free
More information1. For every evaluation of a variable var, the variable is bound.
7 Types We ve seen how we can use interpreters to model the run-time behavior of programs. Now we d like to use the same technology to analyze or predict the behavior of programs without running them.
More informationCS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)
CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part
More informationOverview. CS301 Session 3. Problem set 1. Thinking recursively
Overview CS301 Session 3 Review of problem set 1 S-expressions Recursive list processing Applicative programming A look forward: local variables 1 2 Problem set 1 Don't use begin unless you need a side
More informationCS 342 Lecture 8 Data Abstraction By: Hridesh Rajan
CS 342 Lecture 8 Data Abstraction By: Hridesh Rajan 1 Com S 342 so far So far we have studied: Language design goals, Basic functional programming, Flat recursion over lists, Notion of Scheme procedures
More informationHomework 3 COSE212, Fall 2018
Homework 3 COSE212, Fall 2018 Hakjoo Oh Due: 10/28, 24:00 Problem 1 (100pts) Let us design and implement a programming language called ML. ML is a small yet Turing-complete functional language that supports
More informationNormal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?
Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated
More informationScheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7
Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions
More informationProject 2: Scheme Interpreter
Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same
More informationMid-Term 2 Grades
Mid-Term 2 Grades 100 46 1 HW 9 Homework 9, in untyped class interpreter: Add instanceof Restrict field access to local class Implement overloading (based on argument count) Due date is the same as for
More informationComputer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing
Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible
More informationReview: Concrete syntax for Impcore
Review: Concrete syntax for Impcore Definitions and expressions: def ::= (define f (x1... xn) exp) (val x exp) exp (use filename) (check-expect exp1 exp2) (check-error exp) exp ::= integer-literal ;; atomic
More informationComp 311: Sample Midterm Examination
Comp 311: Sample Midterm Examination October 29, 2007 Name: Id #: Instructions 1. The examination is closed book. If you forget the name for a Scheme operation, make up a name for it and write a brief
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 17: Functional Programming Zheng (Eddy Zhang Rutgers University April 4, 2018 Class Information Homework 6 will be posted later today. All test cases
More informationName EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) )
CS 345 Spring 2010 Midterm Exam Name EID 1. [4 Points] Circle the binding instances in the following expression: (calc (parse '+ with x + 5 5 with y - x 3 + y y z ) ) 2. [7 Points] Using the following
More informationFall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of
1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 1996 Lecture Notes { October 31,
More informationPrinciples of Programming Languages 2017W, Functional Programming
Principles of Programming Languages 2017W, Functional Programming Assignment 3: Lisp Machine (16 points) Lisp is a language based on the lambda calculus with strict execution semantics and dynamic typing.
More informationSEMANTIC ANALYSIS TYPES AND DECLARATIONS
SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether
More informationCSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures
CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught
More informationFlang typechecker Due: February 27, 2015
CMSC 22610 Winter 2015 Implementation of Computer Languages I Flang typechecker Due: February 27, 2015 Project 3 February 9, 2015 1 Introduction The third project is to implement a type checker for Flang,
More informationLecture 12: Conditional Expressions and Local Binding
Lecture 12: Conditional Expressions and Local Binding Introduction Corresponds to EOPL 3.3-3.4 Please review Version-1 interpreter to make sure that you understand how it works Now we will extend the basic
More informationStreams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson
Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation
More informationProcedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt
Data abstractions Abstractions and their variations Basic data abstractions Why data abstractions are useful Procedural abstraction Process of procedural abstraction Define formal parameters, capture process
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Operational Semantics CMSC 330 Summer 2018 1 Formal Semantics of a Prog. Lang. Mathematical description of the meaning of programs written in that language
More information1.3. Conditional expressions To express case distinctions like
Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts
More informationPrinciples of Programming Languages
Principles f Prgramming Languages Slides by Dana Fisman based n bk by Mira Balaban and lecuture ntes by Michael Elhadad Dana Fisman Lessn 16 Type Inference System www.cs.bgu.ac.il/~ppl172 1 Type Inference
More informationLecture 3: Expressions
CS 7400 September 23 30, 2009 Dr. Wand Readings: EOPL3, Secs. 3.1 3.5 Lecture 3: Expressions Key Concepts: syntax and semantics expressed and denoted values expressions environment specifying the behavior
More informationEvaluating Scheme Expressions
Evaluating Scheme Expressions How Scheme evaluates the expressions? (procedure arg 1... arg n ) Find the value of procedure Find the value of arg 1 Find the value of arg n Apply the value of procedure
More informationn n Try tutorial on front page to get started! n spring13/ n Stack Overflow!
Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!
More informationScheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax
Scheme Tutorial Introduction Scheme is an imperative language with a functional core. The functional core is based on the lambda calculus. In this chapter only the functional core and some simple I/O is
More informationBuilding a system for symbolic differentiation
Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)
More informationComp 411 Principles of Programming Languages Lecture 7 Meta-interpreters. Corky Cartwright January 26, 2018
Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters Corky Cartwright January 26, 2018 Denotational Semantics The primary alternative to syntactic semantics is denotational semantics.
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.
More informationAn Explicit-Continuation Metacircular Evaluator
Computer Science (1)21b (Spring Term, 2018) Structure and Interpretation of Computer Programs An Explicit-Continuation Metacircular Evaluator The vanilla metacircular evaluator gives a lot of information
More informationLECTURE 16. Functional Programming
LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative
More informationCSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018 Typical workflow concrete syntax (string) "(fn x => x + x) 4" Parsing Possible errors / warnings
More informationAnnouncements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.
The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper
More informationFP Foundations, Scheme
FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages
More informationCS 275 Name Final Exam Solutions December 16, 2016
CS 275 Name Final Exam Solutions December 16, 2016 You may assume that atom? is a primitive procedure; you don t need to define it. Other helper functions that aren t a standard part of Scheme you need
More informationData Abstraction. An Abstraction for Inductive Data Types. Philip W. L. Fong.
Data Abstraction An Abstraction for Inductive Data Types Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Introduction This lecture
More informationType Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules.
Outline Type Checking General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time
More informationPrinciples of Programming Languages
Ben-Gurion University of the Negev Faculty of Natural Science Department of Computer Science Mira Balaban Lecture Notes April 9, 2013 Many thanks to Tamar Pinhas, Azzam Maraee, Ami Hauptman, Eran Tomer,
More informationOutline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference
Type Checking Outline General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time
More informationAgenda. CS301 Session 9. Abstract syntax: top level. Abstract syntax: expressions. The uscheme interpreter. Approaches to solving the homework problem
CS301 Session 9 The uscheme interpreter Agenda Approaches to solving the homework problem 1 2 Abstract syntax: top level datatype toplevel = EXP of exp DEFINE of name * lambda VAL of name * exp USE of
More informationSpring 2018 Discussion 7: March 21, Introduction. 2 Primitives
CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme
More informationCS422 - Programming Language Design
1 CS422 - Programming Language Design From SOS to Rewriting Logic Definitions Grigore Roşu Department of Computer Science University of Illinois at Urbana-Champaign In this chapter we show how SOS language
More informationBelow are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.
6.001, Fall Semester, 2002 Quiz II Sample solutions 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs
More informationChapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF)
Chapter 3: Describing Syntax and Semantics Introduction Formal methods of describing syntax (BNF) We can analyze syntax of a computer program on two levels: 1. Lexical level 2. Syntactic level Lexical
More informationA Small Interpreted Language
A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that
More informationIntroduction to lambda calculus Part 3
Introduction to lambda calculus Part 3 Antti-Juhani Kaijanaho 2017-01-27... 1 Untyped lambda calculus... 2 Typed lambda calculi In an untyped lambda calculus extended with integers, it is required that
More informationCSE-321: Assignment 8 (100 points)
CSE-321: Assignment 8 (100 points) gla@postech.ac.kr Welcome to the final assignment of CSE-321! In this assignment, you will implement a type reconstruction algorithm (the algorithm W discussed in class)
More informationProgramming Languages
Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages
More informationFall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationCase Study: Undefined Variables
Case Study: Undefined Variables CS 5010 Program Design Paradigms Bootcamp Lesson 7.4 Mitchell Wand, 2012-2017 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International
More information4.2 Variations on a Scheme -- Lazy Evaluation
[Go to first, previous, next page; contents; index] 4.2 Variations on a Scheme -- Lazy Evaluation Now that we have an evaluator expressed as a Lisp program, we can experiment with alternative choices in
More informationCIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL
CIS 194: Homework 3 Due Wednesday, February 11, 2015 Interpreters An interpreter is a program that takes another program as an input and evaluates it. Many modern languages such as Java 1, Javascript,
More informationPrinciples of Programming Languages, Spring 2016 Assignment 5 Logic Programming
Principles of Programming Languages, Spring 2016 Assignment 5 Logic Programming Submission instructions: a. Submit an archive file named id1_id2.zip where id1 and id2 are the IDs of the students responsible
More information11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT
Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the
More informationDenotational Semantics. Domain Theory
Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning
More informationC311 Lab #3 Representation Independence: Representation Independent Interpreters
C311 Lab #3 Representation Independence: Representation Independent Interpreters Will Byrd webyrd@indiana.edu February 5, 2005 (based on Professor Friedman s lecture on January 29, 2004) 1 Introduction
More informationDiscussion 12 The MCE (solutions)
Discussion 12 The MCE (solutions) ;;;;METACIRCULAR EVALUATOR FROM CHAPTER 4 (SECTIONS 4.1.1-4.1.4) of ;;;; STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS ;;;from section 4.1.4 -- must precede def of
More informationCA Compiler Construction
CA4003 - Compiler Construction Semantic Analysis David Sinclair Semantic Actions A compiler has to do more than just recognise if a sequence of characters forms a valid sentence in the language. It must
More informationBuilding a system for symbolic differentiation
Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)
More informationScheme Quick Reference
Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries
More informationA Brief Introduction to Scheme (II)
A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data
More informationProgramming Language Concepts, cs2104 Lecture 04 ( )
Programming Language Concepts, cs2104 Lecture 04 (2003-08-29) Seif Haridi Department of Computer Science, NUS haridi@comp.nus.edu.sg 2003-09-05 S. Haridi, CS2104, L04 (slides: C. Schulte, S. Haridi) 1
More informationFall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationHard deadline: 3/28/15 1:00pm. Using software development tools like source control. Understanding the environment model and type inference.
CS 3110 Spring 2015 Problem Set 3 Version 0 (last modified March 12, 2015) Soft deadline: 3/26/15 11:59pm Hard deadline: 3/28/15 1:00pm Overview In this assignment you will implement several functions
More informationCSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)
CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent
More informationUser-defined Functions. Conditional Expressions in Scheme
User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment
More informationTowards a Module System for K
Towards a Module System for Mark Hills and Grigore Roşu {mhills, grosu}@cs.uiuc.edu Department of Computer Science University of Illinois at Urbana-Champaign WADT 08, 14 June 2008 Hills and Roşu WADT 08:
More informationScheme Quick Reference
Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and
More informationProcedures. EOPL3: Section 3.3 PROC and App B: SLLGEN
Procedures EOPL3: Section 3.3 PROC and App B: SLLGEN The PROC language Expression ::= proc (Identifier) Expression AST: proc-exp (var body) Expression ::= (Expression Expression) AST: call-exp (rator rand)
More informationCSc 520 Principles of Programming Languages
CSc 520 Principles of Programming Languages 9: Scheme Metacircular Interpretation Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian
More informationMeanings of syntax. Norman Ramsey Geoffrey Mainland. COMP 105 Programming Languages Tufts University. January 26, 2015
Meanings of syntax Norman Ramsey Geoffrey Mainland COMP 105 Programming Languages Tufts University January 26, 2015 (COMP 105) Meanings of syntax January 26, 2015 1 / 33 What is the meaning of a while
More informationSyntax and Grammars 1 / 21
Syntax and Grammars 1 / 21 Outline What is a language? Abstract syntax and grammars Abstract syntax vs. concrete syntax Encoding grammars as Haskell data types What is a language? 2 / 21 What is a language?
More informationChapter 15 Functional Programming Languages
Chapter 15 Functional Programming Languages Fundamentals of Functional Programming Languages Introduction to Scheme A programming paradigm treats computation as the evaluation of mathematical functions.
More informationDocumentation for LISP in BASIC
Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have
More informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationSCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015
SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationLexical Addresses. let x = 1 y = 2 in let f = proc (x) +(x, y) in (f x) let _ = 1 _ = 2 in let _ = proc (_) +(<0,0>, <1,1>) in (<0,0> <1,0>)
Lexical Addresses As we saw in the last lecture, the expression might be compiled to let x = 1 y = 2 in let f = proc (x) +(x, y) in (f x) let _ = 1 _ = 2 in let _ = proc (_) +(, ) in ( )
More informationCONVENTIONAL EXECUTABLE SEMANTICS. Grigore Rosu CS422 Programming Language Design
CONVENTIONAL EXECUTABLE SEMANTICS Grigore Rosu CS422 Programming Language Design Conventional Semantic Approaches A language designer should understand the existing design approaches, techniques and tools,
More informationTracing Ambiguity in GADT Type Inference
Tracing Ambiguity in GADT Type Inference ML Workshop 2012, Copenhagen Jacques Garrigue & Didier Rémy Nagoya University / INRIA Garrigue & Rémy Tracing ambiguity 1 Generalized Algebraic Datatypes Algebraic
More informationCOP4020 Spring 2011 Midterm Exam
COP4020 Spring 2011 Midterm Exam Name: (Please print Put the answers on these sheets. Use additional sheets when necessary or write on the back. Show how you derived your answer (this is required for full
More information